/*
	input params:
		1. the p4 path for test
*/
function BuildCraftProcess(callbacker){
	
	this.callbacker=callbacker;
	
	this.handleP4Path=function(path){
		var p4Path=P4Path.fromString(path);

		var stepInfo={
			title:path,//p4Path.projectName+' on '+p4Path.codeLine,//+':'+path,
			time:null,
			onProgressMessage:null,
			onFinish:null
		};
		this.onGetNewStep(stepInfo);
		
		if(p4Path==null){
			stepInfo.title='Invalid path';
			stepInfo.time=new Date();
			if(stepInfo.onFinish)
				stepInfo.onFinish({isSuccess:false});
			return;
		}
		
		if(stepInfo.onProgressMessage)
			stepInfo.onProgressMessage('Get file log');
		
		var r=P4.getFileLog(p4Path.getFullPathWithoutRevision());
		if(!r.isSuccess){
			/*this.callbacker.onException({
				message:'P4.getFileLog error',
				type:'P4.getFileLog',
				innerException:r.exception
			});*/
			stepInfo.title='Invalid path';
			stepInfo.time=new Date();
			if(stepInfo.onFinish)
				stepInfo.onFinish({isSuccess:false});
			return;			
		}
		else
		{
			switch(p4Path.codeLine){
			case 'Dev':
				for(var i=r.logItems.length-1;i>=0;--i)
				{
					var logItem=r.logItems[i];
					if(logItem.revision<p4Path.revision)continue;
					var foundItemWhichHasIntegratedToIntLine=false;
					//check whether this change list has copied into Int line
					for(var j=0;j<logItem.copyList.length;++j)
					{
						if(P4Path.fromString(logItem.copyList[j].path).codeLine=='Int'){
							stepInfo.title=p4Path.projectName+' on '+p4Path.codeLine+' rev:'+logItem.revision,
							stepInfo.time=logItem.time;
							if(stepInfo.onFinish)
								stepInfo.onFinish({isSuccess:true});
							this.handleP4Path(logItem.copyList[j].path);
							foundItemWhichHasIntegratedToIntLine=true;
							break;
						}
					}
					if(foundItemWhichHasIntegratedToIntLine)break;
				}
				if(!foundItemWhichHasIntegratedToIntLine){
					stepInfo.title='Hasn\'t integrated to int line';
					stepInfo.time=new Date();
					if(stepInfo.onFinish)
						stepInfo.onFinish({isSuccess:false});
				}				
				break;
			case 'Int':
				//find build time
				for(var i=0;i<r.logItems.length;++i)
				{
					var logItem=r.logItems[i];
					if(logItem.revision==p4Path.revision)
					{
						stepInfo.title=p4Path.projectName+' on '+p4Path.codeLine+' rev:'+logItem.revision,
						stepInfo.time=logItem.time;
						if(stepInfo.onFinish)
							stepInfo.onFinish({isSuccess:true});
							
						this.handleP4Build(
							{
								projectName:p4Path.projectName,
								language:p4Path.language,
								version:p4Path.version
							}
						,logItem.time);
					}
					
				}

				break;
			default:
				alert(p4Path.codeLine+' codeline not implement');
			}			
		};
	}
	
	this.handleP4Build=function(buildInfo,timeAfter){
		var stepInfo={
			title:'P4 build',
			time:null,
			onProgressMessage:null,
			onFinish:null
		};
		
		this.onGetNewStep(stepInfo);
		
		var innerVersion=buildInfo.version;
		
		switch(buildInfo.projectName){
		case 'CSM':
			buildInfo.p4BuildTag={ProjectName:'CSM'};
			switch(buildInfo.version){
			case '6.0':
				buildInfo.p4BuildTag.version='16.0';
				break;
			}
			break;
		case 'OSCE_common':
			buildInfo.p4BuildTag={ProjectName:'OSCE_COMMON'};
			buildInfo.p4BuildTag.version=buildInfo.version;
			break;
		case 'SMEX':
			buildInfo.p4BuildTag={ProjectName:'SMEX'};
			buildInfo.p4BuildTag.version=buildInfo.version;
			break;
		}
		
		if(stepInfo.onProgressMessage)
			stepInfo.onProgressMessage('Finding label');
		
		var r=P4.exec('labels -m 1000 -u build -e "...'+buildInfo.p4BuildTag.ProjectName+'_'+buildInfo.p4BuildTag.version+'..."');
		var labelLines=r.out.split('\n');
		
		var timeAfterOnlyDate=new Date(timeAfter);
		{
			timeAfterOnlyDate.setHours(0);
			timeAfterOnlyDate.setMinutes(0);
			timeAfterOnlyDate.setSeconds(0);
			timeAfterOnlyDate.setMilliseconds(0);
		}
		
		for(var i=0;i<labelLines.length;i++){
			
			var labelParseResult=/Label ([.\w]+) (\d{4}\/\d{2}\/\d{2})/.exec(labelLines[i]);
			if(labelParseResult==null)continue;
			var labelDate=new Date(labelParseResult[2]);
			var labelName=labelParseResult[1];
			
			if(labelDate<timeAfterOnlyDate)
				continue;
			//check precise time of the label;
			
			var buildNumber=parseInt(/[^.]+.[^.]+.[^.]+.([^.]+)/.exec(labelName)[1]);
			
			var labelDetail=P4.exec('label -o '+labelName);
			//alert(labelDetail.out.split('\nUpdate:')[1]);
			labelTimeMatchResult=/(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2})/m.exec(labelDetail.out.split('\nUpdate:')[1]);
			labelTime=new Date(labelTimeMatchResult[1]);
			if(labelTime<timeAfter)continue;

			stepInfo.time=labelTime;
			stepInfo.title='Included in '+buildInfo.projectName +' build '+buildNumber;
			if(stepInfo.onFinish)
				stepInfo.onFinish({isSuccess:true});

			this.handleTwTestingBuild(buildInfo,buildNumber,labelTime);
			return;
		}
		
		stepInfo.time=new Date();
		stepInfo.title='No '+buildInfo.projectName +' build started after '+timeAfter;
		if(stepInfo.onFinish)
			stepInfo.onFinish({isSuccess:false});
	}
	
	this.handleTwTestingBuild=function(buildInfo,buildAfter,timeAfter){
		var pathItems=[];
		pathItems.push("\\\\tw-testing");
		
		switch(buildInfo.projectName){
		case 'CSM':
			pathItems.push('CSM\\win32');
			switch(buildInfo.version){
			case '6.0':
				pathItems.push("v16.0");
			}
			break;
		case 'OSCE_common':
			pathItems.push('CSM\\win32');
			switch(buildInfo.version){
			case '11.2':
				pathItems.push("v16.0");
				break;
			default:
				alert(buildInfo.version+' not implemented');
			}
			break;
		case 'SMEX':
			pathItems.push('CSM\\win32');
			switch(buildInfo.version){
			case '8.6':
				pathItems.push("v16.0");
				break;
			default:
				alert(buildInfo.version+' not implemented');
			}
			break;
		default:
			alert(buildInfo.projectName+' not implemented');
		}
		
		/*if(buildInfo.language==null){
			pathItems.push("en");
		}else{
			pathItems.push(buildInfo.language);
		}*/
		
		var toCheckLanguages=['en','de','es','fr','it','pl','ru','ja','zh_cn','zh_tw'];
		
		// handle each language
		for(var i=0;i<toCheckLanguages.length;i++){
		
			var stepInfo={
				title:'Checking builds on tw-testing',
				time:null,
				onProgressMessage:null,
				onFinish:null
			};
			this.onGetNewStep(stepInfo);		
		
			var checkingLanguage=toCheckLanguages[i];
			var langPath=pathItems.join('\\')+'\\'+checkingLanguage;

			var foundRequiredBuild=false;
			
			if(!File.objFSO.FolderExists(langPath)){
				stepInfo.title='No '+checkingLanguage+' folder';
				stepInfo.time=new Date();
				if(stepInfo.onFinish)
					stepInfo.onFinish({isSuccess:false});
				continue;
			}
			else
			{
				//get existed builds by searching sub-folder
				var existedBuilds=[];
				{
					var langFolderObj=File.objFSO.GetFolder(langPath);
					var subFoldersIterator=new Enumerator(langFolderObj.SubFolders);
					for (;!subFoldersIterator.atEnd(); subFoldersIterator.moveNext())
					{
						var parseResult=/.+\\(\d{4})/.exec(subFoldersIterator.item());
						if(parseResult!=null){
							existedBuilds.push(parseResult[1]);
						}
					}
					existedBuilds.sort();
				}
				//test each found sub-folders
				
				for(var j=0;j<existedBuilds.length;++j)
				{
					var checkingBuild=existedBuilds[j];

					if(stepInfo.onProgressMessage)
						stepInfo.onProgressMessage('Checking '+checkingLanguage+' build #'+checkingBuild);
					
					var tmpPath=langPath+'\\'+checkingBuild;
					if(!File.objFSO.FolderExists(tmpPath))continue;
					var buildLastAccessedTime=new Date(File.objFSO.GetFolder(tmpPath).DateLastAccessed);
					if(buildLastAccessedTime<timeAfter)continue;
					
					switch(buildInfo.projectName){
					case 'CSM':
						if(parseInt(checkingBuild)<buildAfter)continue;
						
						//must check if the CSM compiled file is existed to avoid build fail case
						var toCheckVersionFilePath=tmpPath+"\\image\\standard_CD\\CSM\\WFBS\\CSMFeature\\cgiRqService.exe";
						if(!File.objFSO.FileExists(toCheckVersionFilePath))continue;
						
						stepInfo.title='Found in '+checkingLanguage+' build '+checkingBuild;
						stepInfo.time=buildLastAccessedTime;
						foundRequiredBuild=true;
						if(stepInfo.onFinish)
							stepInfo.onFinish({isSuccess:true});
						break;
					case 'OSCE_common':
						var toCheckVersionFilePath=tmpPath+"\\image\\standard_CD\\CSM\\WFBS\\CommonFeature\\Pccnt\\TmListenShare.dll";
						if(!File.objFSO.FileExists(toCheckVersionFilePath))continue;
						
						var strVersion=File.objFSO.GetFileVersion(toCheckVersionFilePath);
						var buildNumber=parseInt(/[^.]+.[^.]+.[^.]+.([^.]+)/.exec(strVersion)[1]);
						if(buildNumber<buildAfter)continue;
						
						stepInfo.title='Found in '+checkingLanguage+' build '+checkingBuild+', OSCE build '+buildNumber;
						stepInfo.time=buildLastAccessedTime;
						foundRequiredBuild=true;
						if(stepInfo.onFinish)
							stepInfo.onFinish({isSuccess:true});
						break;
					case 'SMEX':
						var toCheckVersionFilePath=tmpPath+"\\image\\standard_CD\\CSM\\MSA\\utilCsm.dll";
						if(!File.objFSO.FileExists(toCheckVersionFilePath))continue;
						
						var strVersion=File.objFSO.GetFileVersion(toCheckVersionFilePath);
						var buildNumber=parseInt(/[^.]+.[^.]+.[^.]+.([^.]+)/.exec(strVersion)[1]);
						if(buildNumber<buildAfter)continue;
						
						stepInfo.title='Found in '+checkingLanguage+' build '+checkingBuild+', SMEX build '+buildNumber;
						stepInfo.time=buildLastAccessedTime;
						foundRequiredBuild=true;
						if(stepInfo.onFinish)
							stepInfo.onFinish({isSuccess:true});
						break;						
					default:
						alert(" not supported!!");
					}
					if(foundRequiredBuild)
						break;
					else
						alert('error, can\'t find build');
				}
			}
			if(!foundRequiredBuild){
				stepInfo.title="Can't find required build in "+checkingLanguage;
				stepInfo.time=new Date();
				if(stepInfo.onFinish)
					stepInfo.onFinish({isSuccess:false});
			}

		}
		

		

	}
	
	this.onGetNewStep=function(param){
		if(callbacker!=null)
			callbacker.onGetNewStep(param);
	}

};

/*function main(){
	var inputFile=WScript.Arguments(0);
	handleP4Path(inputPath);
}
main();*/
